var url = require('url');
var weiboApi = require('../lib/weiboApi');
var config = require('./config');

// weiboApi.init({
//   app_key: APP_KEY,
//   app_secret: APP_SECRET,
//   app_redirect_uri: APP_REDIRECT_URI
// });
weiboApi.init(config.weibo_app_info);

module.exports = {
  hello: function (req, res) {
    var html = [];
    var uid = req.session.uid;
    var nickname = req.session.nickname || 'nodejs';
    var avatar = req.session.avatar;
    if (uid) {
      html.push('<p><img src="' + avatar + '" /> hello ' + nickname + '.</p>');
      html.push('<p><a href="./create">Create</a></p>');
      html.push('<p><a href="./api/followers?uid=' + uid + '">My Followers</a></p>');
      html.push('<p><a href="./logout">Logout</a></p>');
    } else {
      html.push('<p>hello ' + nickname + '.</p>');
      html.push('<p><a href="./oauth"><img src="/static/img/32.png" /></a></p>');
    }
    render(res, 200, 'text/html', html.join(''));
  },


  oauth: function (req, res) {
    weiboApi.authorize(res);
  },


  oauthCallback: function (req, res) {
    var query = url.parse(req.url, true).query; // true makes query to json
    if (query.code) {
      weiboApi.accessToken(query.code, function (err, data) {
        if (data.error) {
          json(res, {
            error: data.error_description,
            data: null
          });
        } else {
          req.session.uid = data.uid;
          req.session.access_token = data.access_token;
          // json(res, {
          //   error: err,
          //   data: data
          // });
          weiboApi.access_token = data.access_token;
          weiboApi.usersShow({
            uid: data.uid
          }, function (err, data) {
            // console.log('usersShow', err, data);
            req.session.nickname = data.screen_name;
            req.session.avatar = data.profile_image_url;
            redirect(res, './hello');
          });
        }
      });
    } else {
      json(res, {
        error: 'code lost',
        data: null
      });
    }
  },


  logout: function (req, res) {
    req.session = null;
    redirect(res, './hello');
  },


  create: function (req, res) {
    var html = [];
    html.push('<form method="post" action="api/statusesUpdate" enctype="multipart/form-data">');  // enctype="multipart/form-data"
    html.push('<p>CONTENT<br /><textarea name="content" cols="50" rows="4"></textarea></p>');
    html.push('<p>IMG URL<br /><input type="text" name="pic_url" /></p>');
    html.push('<p>UPLOAD IMG<br /><input type="file" name="pic" /></p>');
    html.push('<p><input type="submit" value="POST" /></p>');
    html.push('</form>');
    render(res, 200, 'text/html', html.join(''));
  },

  repost: function (req, res) {
    var query = url.parse(req.url, true).query;
    var html = [];
    html.push('<form method="post" action="api/statusesRepost">');
    html.push('<input type="hidden" name="id" value="' + query.id + '" />');
    html.push('<p>REPOST<br /><textarea name="status" cols="50" rows="4"></textarea></p>');
    html.push('<p><input type="checkbox" name="is_comment" value="1" />with comment</p>');
    html.push('<p><input type="submit" value="POST" /></p>');
    html.push('</form>');
    render(res, 200, 'text/html', html.join(''));
  },


  comment: function (req, res) {
    var query = url.parse(req.url, true).query;
    var html = [];
    html.push('<form method="post" action="api/commentCreate">');
    html.push('<input type="hidden" name="id" value="' + query.id + '" />');
    html.push('<p>COMMENT<br /><textarea name="comment" cols="50" rows="4"></textarea></p>');
    html.push('<p><input type="checkbox" name="comment_ori" value="1" />and repost</p>');
    html.push('<p><input type="submit" value="POST" /></p>');
    html.push('</form>');
    render(res, 200, 'text/html', html.join(''));
  },


  getWebImage: function (req, res) {
    var query = url.parse(req.url, true).query;
    if (query.img_src) {
      weiboApi.getWebImage(query.img_src, function (err, img) {
        if (err) {
          json(res, {
            error: err,
            data: null
          });
        } else {
          showFile(res, img.type, img.data);
        }
      });
    } else {
      json(res, {
        error: 'src lost',
        data: null
      });
    }
  }
};


function json (res, obj) {
  res.writeHead(200, {
    'Content-Type': 'application/json; charset=utf-8'
  });
  res.write(JSON.stringify(obj));
  res.end();
}


function render (res, code, type, content) {
  res.writeHead(code, {
    'Content-Type': type + '; charset=utf-8'
  });
  var header = '<!DOCTYP html><html><head><meta charset="utf-8"></head><body>';
  var footer = '</body></html>';
  res.write(header + content + footer);
  res.end();
}


function redirect (res, url) {
  res.writeHead(302, {
    'Location': url
    //add other headers here...
  });
  res.end();
}


function showFile (res, type, data) {
  res.writeHead(200, {
    'Content-Type': type
  });
  res.write(data, 'binary');
  res.end();
}
